import Card from '@/components/Card';
import { MyChartOption } from '@/components/EchartsComponent';
import HealthReport from '@/components/HealthReport';
import AreaList from '@/pages/OverView/components/AreaList';
import BatteryCard, { Battery } from '@/pages/OverView/components/BatteryCard';
import BatteryInfo from '@/pages/OverView/components/BatteryInfo';
import DischargeInfo from '@/pages/OverView/components/DischargeInfo';
import EventInfo, { EventInfoRef } from '@/pages/OverView/components/EventInfo';
import OperatingInfo from '@/pages/OverView/components/OperatingInfo';
import PeakValleyChart, { FengguPeriod } from '@/pages/OverView/components/Peaks';
import PowerStatistics from '@/pages/OverView/components/PowerStatistics';
import { PowerView } from '@/pages/OverView/components/PowerView';
import WorkingConditionChart, { StatePeriod } from '@/pages/OverView/components/WorkingDiagram';
import {
  mainPageControllerGetPowerReport,
  mainPageControllerGetReport,
} from '@/services/ess/mainpageStation';
import { stationAreaControllerImplListStationArea } from '@/services/ess/stationArea';
import { formatEmptyValue } from '@/utils';
import { useMediaQuery } from '@/utils/useMediaQuery';
import { useIntl, useModel } from '@umijs/max';
import { Col, Flex, Radio, RadioChangeEvent, Row, Tooltip } from 'antd';
import cls from 'classnames';
import { TimeInterval } from 'd3-time';
import dayjs from 'dayjs';
import { throttle } from 'lodash';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'umi';
import IncomeStatistics from './components/IncomeStatistics';
import PowerChart from './components/PowerChart';
import Styles from './index.less';
import PhotovoltaicComponent from './index_photovoltaic';
import { BatteryEvents } from './OldStation/BatteryEvents';
import { DailyChargeDischargeConversionEfficiency } from './OldStation/DailyChargeDischargeConversionEfficiency';
import { DailyDischargeDepthCurve } from './OldStation/DailyDischargeDepthCurve';
import { PerformanceMetrics } from './OldStation/PerformanceMetrics';
import { timeToDecimal } from './utils/tools';
import { useFetchHomeData } from './utils/useFetchHomeData';
// interface CoordinateItem {
//   x: number;
//   y: number;
//   value: number | string | undefined;
//   detail: { name: string };
// }

// const socNameMap = new Map([
//   ['box', '箱名称'],
//   ['stack', '堆名称'],
//   ['cluster', '簇名称'],
// ]);
// const socNoMap = new Map([
//   ['box', '箱编号'],
//   ['stack', '堆编号'],
//   ['cluster', '簇编号'],
// ]);
const OverView: React.FC = () => {
  // let timeIntervalTask: TimeInterval;
  let chartIntervalTask: TimeInterval;
  let powerIntervalTask: TimeInterval;
  const { initialState, setInitialState } = useModel('@@initialState');
  const isPhotovoltaic = initialState?.isPhotovoltaic;
  const currentArea = useRef(null);
  const eventInfoRef = useRef<EventInfoRef>(null);
  const protocols = initialState?.protocols;
  const isOldStation = protocols?.length === 1 && protocols?.[0] === 'SOCKET';
  const intl = useIntl();
  const isEnglish = intl.locale === 'en-US';
  // 收益统计
  const [incomeInfoOptions, setIncomeInfoOptions] = useState<MyChartOption>();
  const [incomeEndTime, setIncomeEndTime] = useState<string>(dayjs().format('YYYY-MM-DD'));
  const [incomeStartTime, setIncomeStartTime] = useState<string>(
    dayjs().subtract(6, 'day').format('YYYY-MM-DD'),
  );
  const [areaList, setAreaList] = useState<API.StationAreaDTO>();
  const [incomeUnit, setIncomeUnit] = useState<string>('day');
  // 充放电量统计
  const [chargeInfoOptions, setChartInfoOptions] = useState<MyChartOption>();
  const [chargeStartTime, setChargeStartTime] = useState<string>(dayjs().format('YYYY-MM-DD'));
  const [chargeEndTime, setChargeEndTime] = useState<string>(dayjs().format('YYYY-MM-DD'));
  const [chargeUnit, setChargeUnit] = useState<string>('day');
  // 充放电量功率
  const [powerChartInfo, setPowerChartInfo] = useState<MyChartOption>();
  // 发电用电功率
  const [usePowerChartInfo, setUsePowerChartInfo] = useState<MyChartOption>();
  // 发电用电统计
  const [useIncomeChartInfo, setUseIncomeChartInfo] = useState<MyChartOption>();
  /**
   * 获得收益统计chartOptions
   * @param options
   */
  const formatterIncomeOptions = (options: API.ReportTable, unit?: string): MyChartOption => {
    // 确保 options?.xaxis 是一个数组
    const xAxis = options?.xaxis || [];

    // 确保 options?.yaxis[0]?.points 是一个数组
    const yAxisMap = (options?.yaxis[0]?.points || []).reduce((acc, current) => {
      acc[current.xaxis] = current.yaxis;
      return acc;
    }, {});

    // 生成 seriesData 数组
    const seriesData = xAxis.map((date) => {
      return yAxisMap[date] !== undefined ? yAxisMap[date] : 0;
    });

    // 使用 reduce 方法找到 seriesData 中的最大数字
    const maxNum = [seriesData].reduce((acc, cur) => {
      // 过滤出 cur 中的所有数字并找到其中的最大值
      const maxInCur = Math.max(...(cur?.filter((item) => typeof item === 'number') || []));
      // 返回当前最大值和累积最大值中的较大者
      return maxInCur > acc ? maxInCur : acc;
    }, 0);

    return {
      xAxis: {
        type: 'category',
        data: xAxis,
        axisTick: {
          alignWithLabel: true,
        },
        axisLabel: {
          formatter: function (value) {
            return unit === 'day' ? value.split('-')[1] + '-' + value.split('-')[2] : value;
          },
        },
      },
      grid: {
        left: maxNum > 100000 ? 65 : 50,
        top: 35,
        right: 20,
        bottom: 30,
      },
      dataZoom: { type: 'inside' },
      tooltip: {
        show: true,
        trigger: 'axis',
      },
      yAxis: {
        name: options?.unit,
        type: 'value',
        axisLine: {
          show: true,
        },
      },
      series: [
        {
          data: seriesData,
          itemStyle: {
            color: '#1A6CFE',
          },
          type: 'bar',
        },
      ],
    };
  };

  // const addOneHour = (timeString: string) => {
  //   const [hour, minute, second] = timeString.split(':').map((item) => parseInt(item));
  //   const date = new Date();
  //   date.setHours(hour);
  //   date.setMinutes(minute);
  //   date.setSeconds(second);
  //   date.setHours(date.getHours() + 1);
  //   return `${date.getHours().toString().padStart(2, '0')}:${date
  //     .getMinutes()
  //     .toString()
  //     .padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
  // };
  /**
   * 获得充放电量统计
   * @param options
   */
  const formatterChargeOptions = (options: API.ReportTable): MyChartOption => {
    if (options?.yaxis) {
      const xAxis = options?.xaxis;
      const unit = options.unit;

      // 处理所有数据
      const seriesData = options.yaxis
        .map((item, index) => {
          const dataMap = (item?.points || []).reduce((acc, current) => {
            acc[current.xaxis] = current.yaxis;
            return acc;
          }, {});

          const data = xAxis.map((date) => {
            return dataMap[date] !== undefined ? dataMap[date] : '';
          });

          // 判断是否为充电量或放电量(前两个必显示)
          if (index < 2) {
            const colors = ['#48ABFF', '#1A6CFE'];
            const names = [
              intl.formatMessage({ id: 'overviewPages.chargeAmount' }),
              intl.formatMessage({ id: 'overviewPages.dischargeAmount' }),
            ];

            return {
              name: names[index],
              data: data,
              type: 'bar',
              stack: 'total',
              itemStyle: {
                color: colors[index],
              },
            };
          }

          // 对于上下网电量,需要判断数据是否存在
          // 通过检查数据中是否有非空值来判断
          const hasValidData = data.some((value) => value !== null);
          if (hasValidData) {
            const config = {
              2: {
                color: '#56D433',
                name: intl.formatMessage({ id: 'overviewPages.onGridAmount' }),
              },
              3: {
                color: '#67C23A',
                name: intl.formatMessage({ id: 'overviewPages.offGridAmount' }),
              },
            }[index];

            if (config) {
              return {
                name: config.name,
                data: data,
                type: 'bar',
                stack: 'total',
                itemStyle: {
                  color: config.color,
                },
              };
            }
          }

          return null;
        })
        .filter(Boolean); // 过滤掉空值

      // 计算最大堆叠值用于调整左侧边距
      const maxNum = xAxis.reduce((acc, date) => {
        const sum = seriesData.reduce((sum, series) => {
          const value = series.data[xAxis.indexOf(date)];
          return sum + (typeof value === 'number' ? value : 0);
        }, 0);
        return Math.max(acc, sum);
      }, 0);

      return {
        xAxis: {
          type: 'category',
          data: xAxis,
          boundaryGap: true,
          axisTick: {
            alignWithLabel: true,
          },
          axisLabel: {
            formatter: function (value) {
              return value.length === 19
                ? value.slice(11, 13)
                : value.length === 10
                ? value.slice(8, 10)
                : value.slice(5, 7);
            },
          },
        },
        grid: isOldStation
          ? {
              top: 35,
              right: 0,
              left: 0,
              bottom: 0,
              containLabel: true,
            }
          : {
              left: maxNum > 100000 ? 65 : 50,
              top: 35,
              right: 20,
              bottom: 30,
            },
        yAxis: {
          name: unit,
          type: 'value',
          axisLine: {
            show: true,
          },
          nameTextStyle: isOldStation ? { align: 'left' } : {},
        },
        tooltip: {
          show: true,
          trigger: 'axis',
          formatter: function (params) {
            let result = params[0].axisValue;
            params.forEach((param) => {
              result += `<br/>${param.marker}${param.seriesName}: ${formatEmptyValue(param.value)}`;
            });
            return result;
          },
        },
        legend: {
          show: true,
          top: 10,
          right: 0,
          icon: 'circle',
        },
        series: seriesData,
      };
    }
    return {};
  };

  /**
   * 获得当日充放电功率图
   * @param options
   */
  const formatterPowerChartOptions = (options): MyChartOption => {
    // const xAxis = options?.yaxis[0].points.map((item) => {
    //   return item.xaxis;
    // });
    // const yaxis = options?.yaxis[0].points.map((item) => {
    //   return item.yaxis;
    // });
    const seriesData = options?.xaxis.map((item) => {
      const obj = options?.yaxis[0].points.find((obj) => obj.xaxis === item);
      return obj ? obj?.yaxis : '';
    });
    return {
      grid: isOldStation
        ? {
            top: 30,
            right: 0,
            left: 0,
            bottom: 0,
            containLabel: true,
          }
        : {
            top: 40,
            left: 50,
            right: 0,
            bottom: 24,
          },
      dataZoom: { type: 'inside' },
      xAxis: {
        boundaryGap: true,
        type: 'category',
        data: options?.xaxis,
        axisLabel: {
          formatter: function (value) {
            return `${value.split(' ')[1].slice(0, 2)}`;
          },
          interval: 119,
        },
        axisTick: {
          alignWithLabel: true,
        },
      },
      tooltip: {
        trigger: 'item',
        formatter: `{b}<br/>${intl.formatMessage({ id: 'overviewPages.curvePower' })} {c}`,
      },
      yAxis: {
        type: 'value',
        name: options?.unit || 'kWh',
        axisLine: {
          show: true,
        },
        nameTextStyle: isOldStation ? { align: 'left' } : {},
      },
      series: [
        {
          name: 'power',
          connectNulls: true,
          type: 'line',
          data: seriesData,
          smooth: true,
          symbolSize: 1,
          lineStyle: {
            color: '#1A6CFE',
            // width: 4,
            // shadowColor: '#1A6CFE',
            // shadowBlur: 30,
            // shadowOffsetY: 10,
          },
        },
      ],
    };
  };
  /**
   * 用电发电功率
   * @param options
   */
  const formatterUsePowerChart = (options) => {
    // 用电
    const seriesData1 = options?.xaxis.map((item) => {
      const obj = options?.yaxis[0].points.find((obj) => obj.xaxis === item);
      return obj ? obj?.yaxis : '';
    });
    // 发电
    const seriesData2 = options?.xaxis.map((item) => {
      const obj = options?.yaxis[1].points.find((obj) => obj.xaxis === item);
      return obj ? obj?.yaxis : '';
    });
    return {
      grid: isOldStation
        ? {
            top: 30,
            right: 0,
            left: 0,
            bottom: 0,
            containLabel: true,
          }
        : {
            top: 40,
            left: 50,
            right: 0,
            bottom: 24,
          },
      dataZoom: { type: 'inside' },
      legend: {
        right: 0,
      },
      xAxis: {
        boundaryGap: true,
        type: 'category',
        data: options?.xaxis,
        axisLabel: {
          formatter: function (value) {
            return `${value.split(' ')[1].slice(0, 2)}`;
          },
          interval: 119,
        },
        axisTick: {
          alignWithLabel: true,
        },
      },
      tooltip: {
        trigger: 'item',
        formatter: `{b}<br/>${intl.formatMessage({ id: 'overviewPages.curvePower' })} {c}`,
      },
      yAxis: {
        type: 'value',
        name: options?.unit || 'kWh',
        axisLine: {
          show: true,
        },
        nameTextStyle: isOldStation ? { align: 'left' } : {},
      },
      series: [
        {
          name: options?.yaxis[0].title,
          connectNulls: true,
          type: 'line',
          data: seriesData1,
          smooth: true,
          symbolSize: 1,
          lineStyle: {
            color: '#1A6CFE',
            // width: 4,
            // shadowColor: '#1A6CFE',
            // shadowBlur: 30,
            // shadowOffsetY: 10,
          },
        },
        {
          name: options?.yaxis[1].title,
          connectNulls: true,
          type: 'line',
          data: seriesData2,
          smooth: true,
          symbolSize: 1,
          lineStyle: {
            color: '#67C23A',
            // width: 4,
            // shadowColor: '#1A6CFE',
            // shadowBlur: 30,
            // shadowOffsetY: 10,
          },
        },
      ],
    };
  };
  /**
   * 用电发电统计
   * @param options
   */
  const formatterUseIncomeChart = (options: any) => {
    // 用电
    const seriesData1 = options?.xaxis.map((item) => {
      const obj = options?.yaxis[0].points.find((obj) => obj.xaxis === item);
      return obj ? obj?.yaxis : '';
    });
    // 发电
    const seriesData2 = options?.xaxis.map((item) => {
      const obj = options?.yaxis[1].points.find((obj) => obj.xaxis === item);
      return obj ? obj?.yaxis : '';
    });
    return {
      grid: isOldStation
        ? {
            top: 30,
            right: 0,
            left: 0,
            bottom: 0,
            containLabel: true,
          }
        : {
            top: 40,
            left: 50,
            right: 0,
            bottom: 20,
          },
      dataZoom: { type: 'inside' },
      xAxis: {
        boundaryGap: true,
        type: 'category',
        data: options?.xaxis,

        axisTick: {
          alignWithLabel: true,
        },
      },
      tooltip: {
        trigger: 'axis',
      },
      yAxis: {
        type: 'value',
        name: options?.unit || 'kWh',
        axisLine: {
          show: true,
        },
        nameTextStyle: isOldStation ? { align: 'left' } : {},
      },
      series: [
        {
          name: options?.yaxis[0].title,
          connectNulls: true,
          type: 'bar',
          data: seriesData1,
          smooth: true,
          symbolSize: 1,
          lineStyle: {
            color: '#1A6CFE',
            // width: 4,
            // shadowColor: '#1A6CFE',
            // shadowBlur: 30,
            // shadowOffsetY: 10,
          },
        },
        {
          name: options?.yaxis[1].title,
          connectNulls: true,
          type: 'bar',
          data: seriesData2,
          smooth: true,
          symbolSize: 1,
          lineStyle: {
            color: '#67C23A',
            // width: 4,
            // shadowColor: '#1A6CFE',
            // shadowBlur: 30,
            // shadowOffsetY: 10,
          },
        },
      ],
    };
  };
  /**
   * 获得发电用电功率
   * @param params
   */
  // const formatterUsePowerOptions = (options): MyChartOption => {};
  const getChartInfo = (params) => {
    const chargeParams = {
      areaId: params.areaId,
      statsType: 'charging',
      statsUnit: params.chargeUnit,
      startTime: params.chargeStartTime,
      endTime: params.chargeEndTime,
    };
    const incomeParams = {
      areaId: params.areaId,
      statsType: 'income',
      statsUnit: params.incomeUnit,
      startTime: params.incomeStartTime,
      endTime: params.incomeEndTime,
    };
    mainPageControllerGetReport(chargeParams).then((res) => {
      setChartInfoOptions(formatterChargeOptions(res?.data, res?.data?.unit));
    });
    mainPageControllerGetReport(incomeParams).then((res) => {
      setIncomeInfoOptions(formatterIncomeOptions(res?.data));
    });
  };

  /**
   * 获得功率图
   */
  const getPowerChartInfo = () => {
    if (eventInfoRef.current) {
      eventInfoRef.current.pauseScrolling();
    }

    mainPageControllerGetPowerReport({
      stationId: initialState?.stationId,
      areaId: currentArea?.current?.id,
    }).then((res) => {
      setPowerChartInfo(formatterPowerChartOptions(res?.data));
      if (eventInfoRef.current) {
        eventInfoRef.current.resumeScrolling();
      }
    });
  };

  /**
   * 获得光储充发电/用电统计
   */
  const getPhotovoChartInfo = (unit = 'month') => {
    const params = {
      areaId: currentArea?.current?.id,
      statsType: 'generate',
      statsUnit: unit,
      startTime: unit === 'month' ? dayjs().format('YYYY-MM') : dayjs().format('YYYY'),
    };
    mainPageControllerGetReport(params).then((res) => {
      console.log('发电用电', res);
      setUseIncomeChartInfo(formatterUseIncomeChart(res.data));
    });
  };
  const changeIncomeType = (type: string) => {
    getPhotovoChartInfo(type);
  };
  useEffect(() => {
    if (isPhotovoltaic) {
      mainPageControllerGetPowerReport({
        stationId: initialState?.stationId,
        areaId: currentArea?.current?.id,
        type: 'generate',
      }).then((res) => {
        setUsePowerChartInfo(formatterUsePowerChart(res.data));
      });
      getPhotovoChartInfo();
    }
  }, [isPhotovoltaic]);
  // const getMainPageInfo = (params: API.mainPageControllerGetMainPageInfoParams) => {
  //   mainPageControllerGetMainPageInfo(params).then((res) => {
  //     if (res.success && res?.data && Object.keys(res.data).length > 0) {
  //       if (res.data.deviceVOs) {
  //       }
  //     }
  //   });
  // };
  /**
   * 收益统计查询
   * @param value
   */
  const getIncomeInfo = (value) => {
    const params = {
      areaId: currentArea?.current?.id,
      stationId: initialState?.stationId,
      incomeStartTime: value.incomeStartTime,
      incomeEndTime: value.incomeEndTime,
      incomeUnit: value.incomeUnit,
      chargeStartTime: chargeStartTime,
      chargeEndTime: chargeEndTime,
      chargeUnit: chargeUnit,
    };
    getChartInfo(params);
    setIncomeStartTime(value.incomeStartTime);
    setIncomeEndTime(value.incomeEndTime);
    setIncomeUnit(value.incomeUnit);
  };
  /**
   * 充放电量统计查询
   * @param value
   */
  const getChargeInfo = (value) => {
    const params = {
      areaId: currentArea?.current?.id,
      stationId: initialState?.stationId,
      incomeStartTime: incomeStartTime,
      incomeEndTime: incomeEndTime,
      incomeUnit: incomeUnit,
      chargeStartTime: value.chargeStartTime,
      chargeUnit: value.chargeUnit,
    };
    getChartInfo(params);
    setChargeStartTime(value.chargeStartTime);
    setChargeEndTime(value.chargeEndTime);
    setChargeUnit(value.chargeUnit);
  };
  // /**
  //  * 每十秒刷新页面的回调函数
  //  * @param params
  //  */
  // const gerRefreshPageInfo = (params) => {
  //   mainPageControllerGetMainPageInfo(params).then((res) => {
  //     if (res.success && res.data && Object.keys(res.data).length > 0) {
  //       //soc相关数据增加实时更新
  //       if (res.data.deviceVOs) {
  //       }
  //
  //       // setPowerChartInfo(formatterPowerChartOptions(res?.data?.dailyPowerReport));
  //     }
  //   });
  // };

  const throttledGetPowerChartInfo = throttle(getPowerChartInfo, 10000);
  /**
   * 获得分区列表
   */
  useEffect(() => {
    if (initialState?.areaInfo) {
      currentArea.current = initialState?.areaInfo;
      const params = {
        areaId: currentArea?.current?.id,
        stationId: initialState?.stationId,
        incomeStartTime: incomeStartTime,
        incomeEndTime: incomeEndTime,
        incomeUnit: incomeUnit,
        chargeStartTime: chargeStartTime,
        chargeUnit: chargeUnit,
      };
      getChartInfo(params);
    }
  }, [initialState?.areaInfo]);

  useEffect(() => {
    if (initialState?.stationId) {
      stationAreaControllerImplListStationArea().then((res) => {
        setInitialState((s) => ({
          ...s,
          areaInfo: res?.data[0],
        }));
        setAreaList(res?.data);
      });
    }
    // if (timeIntervalTask) {
    //   clearInterval(timeIntervalTask);
    // }
    if (chartIntervalTask) {
      clearInterval(chartIntervalTask);
    }
    if (powerIntervalTask) {
      clearInterval(powerIntervalTask);
    }
    if (initialState?.stationId) {
      // fetchDictInfo(DATABASE_TYPE_ENUM.SITE_TYPE).then((res) => {
      // });
      // fetchDictInfo(DATABASE_TYPE_ENUM.OVERVIEW_RUN_STATUS, true).then((res) => {

      // });

      const params = {
        areaId: currentArea?.current?.id,
        stationId: initialState?.stationId,
        incomeStartTime: incomeStartTime,
        incomeEndTime: incomeEndTime,
        incomeUnit: incomeUnit,
        chargeStartTime: chargeStartTime,
        chargeUnit: chargeUnit,
      };
      getChartInfo(params);
      getPowerChartInfo();
      // timeIntervalTask = setInterval(() => {
      //   gerRefreshPageInfo(params);
      // }, 10000);
      chartIntervalTask = setInterval(() => {
        getChartInfo(params);
      }, 3600000);
      powerIntervalTask = setInterval(() => {
        throttledGetPowerChartInfo();
      }, 2000);
      // return () => clearInterval(powerIntervalTask);
    }

    return () => {
      // clearInterval(timeIntervalTask);
      clearInterval(chartIntervalTask);
      clearInterval(powerIntervalTask);
    };
  }, [initialState?.stationId]);

  const {
    stationStatuses,
    stationRealStatuses,
    stationBaseStatus,
    stationBatteryData,
    stationMainData,
    stationBaseData,
    stationWarningEvent,
    stationPolicyEvent,
    stationWorkState,
    stationChargeAndDischarge,
    photovolaticStatuses,
    stationRealtimeData,
  } = useFetchHomeData(
    initialState?.stationId,
    isOldStation,
    initialState?.areaInfo?.id,
    isPhotovoltaic,
  );
  // 基础概况面板
  const BaseTimePanel = () => {
    return <PowerView statuses={stationBaseStatus} />;
  };

  // 实时概况面板
  const RealTimePanel = () => {
    return <PowerView statuses={stationRealStatuses} />;
  };

  const [batteryInfoSelected, setBatteryInfoSelected] = useState('realTime');
  const [batteryEventelected, setBatteryEventSelected] = useState(
    protocols?.includes('GLC') ? 'warningEvent' : 'baseEvent',
  );

  const handleChangeStatus = (e: RadioChangeEvent) => {
    setBatteryInfoSelected(e.target.value);
  };

  const materials: Battery[] = [
    {
      type: 'battery',
      title: intl.formatMessage({ id: 'overviewPages.batteryBoxs' }),
      materialsNumber: stationMainData?.boxCount,
      link: '/monitor/equipmentView',
    },
    {
      type: 'cabinet',
      title: intl.formatMessage({ id: 'overviewPages.batteryCabinets' }),
      materialsNumber: stationMainData?.cabinetCount,
      link: '/monitor/equipmentView',
    },
    {
      type: 'pcs',
      title: intl.formatMessage({ id: 'overviewPages.pcs' }),
      materialsNumber: stationMainData?.pcsCount,
      link: '/monitor/equipmentView',
    },
    {
      type: 'cell',
      title: intl.formatMessage({ id: 'overviewPages.cells' }),
      materialsNumber: stationMainData?.cellCount,
      link: '/monitor/equipmentView',
    },
  ];

  // 过滤掉 materialsNumber 不是数字的对象
  const filteredMaterials = materials.filter((material) => {
    // 确保 materialsNumber 是一个数字且不是 NaN
    return typeof material.materialsNumber === 'number' && !isNaN(material.materialsNumber);
  });

  const handleChangeEvent = (e: RadioChangeEvent) => {
    setBatteryEventSelected(e.target.value);
  };

  // 策略事件
  const BaseEventPanel = () => {
    return <EventInfo eventData={stationPolicyEvent} columnWidths={['50px', '150px', '60px']} />;
  };

  // 警告事件
  const WarningEventPanel = () => {
    const isScrolling = stationWarningEvent.length > 4;
    return (
      <EventInfo
        eventData={stationWarningEvent}
        eventType="warning"
        isScrolling={isScrolling}
        columnWidths={['50px', '80px', '200px']}
      />
    );
  };

  // 根据不同的事件类型设置链接地址
  const linkTo = batteryEventelected === 'baseEvent' ? '/strategy/track?tab=3' : '/alarm/list';

  // 24 小时工况图
  // 定义国际化ID与数字键的映射关系
  const i18nLabelMap = {
    1: 'global.sharp',
    2: 'global.peak',
    3: 'global.shoulder',
    4: 'global.offPeak',
  };

  // 生成国际化后的labelMap
  const labelMap: { [key: string]: string } = {};
  for (const [key, value] of Object.entries(i18nLabelMap)) {
    labelMap[key] = intl.formatMessage({ id: value });
  }

  // 定义国际化ID与原始中文键的映射关系
  const i18nColorMap = {
    充电: 'global.charge',
    放电: 'global.discharge',
    静置: 'global.standby',
    调试: 'global.debug',
    检修: 'global.maintain',
    故障: 'global.fault',
  };

  // 定义颜色映射对象
  const colorMap = {
    充电: '#56D433',
    放电: '#1A6CFE',
    静置: '#FFD50C',
    调试: '#8662F1',
    检修: '#FF7A0C',
    故障: '#FF5353',
  };

  const ColorMapComponent = () => {
    const intl = useIntl();

    // 生成国际化后的颜色映射对象
    const intlColorMap = {};
    for (const [key, value] of Object.entries(colorMap)) {
      const intlKey = intl.formatMessage({ id: i18nColorMap[key] });
      console.log(`Key: ${key}, IntlKey: ${intlKey}`);
      intlColorMap[intlKey] = value;
    }

    return (
      <div className={Styles.colorMapWrap}>
        {Object.entries(intlColorMap).map(([key, value]) => (
          <p key={key}>
            <span
              style={{
                backgroundColor: value as string,
                display: 'inline-block',
                width: '12px',
                height: '12px',
                borderRadius: '2px',
              }}
            ></span>
            <span style={{ marginLeft: '5px' }}>{key}</span>
          </p>
        ))}
      </div>
    );
  };

  const [fengGuData, setFengGuData] = useState<FengguPeriod[]>([]);
  const [workStateData, setWorkStateData] = useState<StatePeriod[]>([]);
  useEffect(() => {
    // 清空数据
    setFengGuData([]);
    setWorkStateData([]);

    if (stationWorkState) {
      if (stationWorkState.fenggu) {
        const newFengGuData: FengguPeriod[] =
          stationWorkState?.fenggu?.map((item) => {
            const label =
              item.timeType !== undefined && labelMap.hasOwnProperty(item.timeType)
                ? labelMap[item.timeType]
                : '--';

            return {
              name: label,
              startTime: timeToDecimal(item.startTime as string),
              endTime: timeToDecimal(item.endTime as string),
              label: label,
            };
          }) || [];
        setFengGuData(newFengGuData);
      } else {
        setFengGuData([]);
      }
      if (stationWorkState.workstate && stationWorkState.workstate.length) {
        const newWorkStateData: StatePeriod[] =
          stationWorkState?.workstate?.map((item) => {
            const color =
              item.workstateName && colorMap.hasOwnProperty(item.workstateName)
                ? colorMap[item.workstateName]
                : '#000000';
            const label =
              item.workstate !== undefined && labelMap.hasOwnProperty(item.workstate)
                ? labelMap[item.workstate]
                : '--';

            return {
              name: item.workstateName || '--',
              startTime: timeToDecimal(item.startTime),
              endTime: timeToDecimal(item.endTime),
              color: color,
              label: label,
            };
          }) || [];
        setWorkStateData(newWorkStateData);
      } else {
        console.log('无工况数据');
        setWorkStateData([]);
      }
    }
  }, [stationWorkState]);
  const isWide = useMediaQuery('(max-width: 1620px)');
  const isSmallViewport = useMediaQuery('(max-width: 1440px)');
  const isWideFlex = isWide ? '1 1 100%' : '1 1';

  // old station with new ui
  // 1. 电站概况
  const overviewOfPowerPlant = (
    <Card
      title={intl.formatMessage({ id: 'overviewPages.plantOverview' })}
      style={{ height: '100%' }}
      extra={
        <Radio.Group
          defaultValue="realTime"
          buttonStyle="solid"
          onChange={handleChangeStatus}
          value={batteryInfoSelected}
          size="small"
        >
          <Radio.Button value="realTime">
            {intl.formatMessage({ id: 'overviewPages.realTime' })}
          </Radio.Button>
          <Radio.Button value="baseTime">
            {intl.formatMessage({ id: 'overviewPages.baseTime' })}
          </Radio.Button>
        </Radio.Group>
      }
    >
      {batteryInfoSelected === 'realTime' ? <RealTimePanel /> : <BaseTimePanel />}
    </Card>
  );
  // 2. 运行指标
  const performanceMetrics = <PerformanceMetrics style={{ height: '100%' }} />;
  // 3. 充放电量统计
  const chargeAndDischargeStatistics = (
    <Card
      title={intl.formatMessage({ id: 'overviewPages.chargeDischargeStatistics' })}
      style={{ height: '100%' }}
    >
      <PowerStatistics
        chargeInfoOptions={chargeInfoOptions}
        sendChargeInfo={getChargeInfo}
        isOldStation={isOldStation}
      />
    </Card>
  );
  // 4. 当日充放电功率图
  const chargeAndDischargePowerCurve = (
    <Card
      style={{ height: '100%' }}
      title={intl.formatMessage({ id: 'overviewPages.dayChargeDischarge' })}
    >
      <PowerChart powerChartInfo={powerChartInfo} isOldStation={isOldStation} />
    </Card>
  );
  // 5. 电池信息
  const batteryInfo = (
    <Card
      title={intl.formatMessage({ id: 'overviewPages.betteryInfor' })}
      style={{ height: '100%' }}
      extra={
        <Link to={`/stationmonitor/realtime?battery=true`}>
          <div
            className={Styles.DetailText}
            style={{ marginLeft: '10px', cursor: 'pointer', fontSize: '12px' }}
          >
            <span>{intl.formatMessage({ id: 'global.detail' })}</span>
            <span>{'>'}</span>
          </div>
        </Link>
      }
    >
      {stationBatteryData.map((battery, index) => (
        <BatteryInfo
          key={index}
          stationSoc={battery?.stationSoc}
          soc={{
            min: battery?.soc?.min,
            max: battery?.soc?.max,
            boxName: battery?.soc?.boxName,
          }}
          temperature={{
            min: battery?.temperature?.min,
            max: battery?.temperature?.max,
            boxName: battery?.temperature?.boxName,
          }}
          voltageExtreme={{
            min: battery?.voltageExtreme?.min,
            max: battery?.voltageExtreme?.max,
            boxName: battery?.voltageExtreme?.boxName,
          }}
          currentExtreme={{
            min: battery?.currentExtreme?.min,
            max: battery?.currentExtreme?.max,
            boxName: battery?.currentExtreme?.boxName,
          }}
          isOldStation={isOldStation}
        />
      ))}
    </Card>
  );

  const powerChartCardTitle = (
    <div>
      <Flex justify={'space-between'} align={'center'}>
        <div className={Styles.titleOverflow}>
          <Tooltip
            title={`${intl.formatMessage({
              id: 'overviewPages.dayChargeDischarge',
            })}
                  ${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}
          >
            <div
              style={{
                width: '15rem',
                whiteSpace: 'nowrap' /* 不换行 */,
                textAlign: 'left',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
              }}
            >{`${intl.formatMessage({
              id: 'overviewPages.dayChargeDischarge',
            })}
                  ${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}</div>
          </Tooltip>
        </div>
        <div>
          <Link to={'/strategy/track?tab=2'}>
            <div
              className={Styles.DetailText}
              style={{ fontSize: '14px', cursor: 'pointer', fontWeight: 'normal' }}
            >
              <span>{intl.formatMessage({ id: 'global.detail' })}</span>
              <span>{'>'}</span>
            </div>
          </Link>
        </div>
      </Flex>
    </div>
  );

  return !isOldStation ? (
    isPhotovoltaic ? (
      <PhotovoltaicComponent
        photovolaticStatuses={photovolaticStatuses}
        stationBaseData={stationBaseData}
        stationMainData={stationMainData}
        stationWarningEvent={stationWarningEvent}
        stationPolicyEvent={stationPolicyEvent}
        stationRealtimeData={stationRealtimeData}
        areaList={areaList}
        powerChartInfo={powerChartInfo}
        chargeInfoOptions={chargeInfoOptions}
        useIncomeChartInfo={useIncomeChartInfo}
        usePowerChartInfo={usePowerChartInfo}
        changeIncomeType={changeIncomeType}
        getChargeInfo={getChargeInfo}
      />
    ) : (
      <div className={Styles.view}>
        <div className={cls([intl.locale === 'en-US' ? Styles.carousel_EN : Styles.carousel])}>
          <AreaList areaList={areaList}></AreaList>
        </div>
        <Row gutter={20}>
          <Col
            flex={isWideFlex}
            style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}
          >
            <div className={Styles.BatteryInfoWrap}>
              <div className={Styles.BatteryInfoBox}>
                <Card
                  title={`${intl.formatMessage({ id: 'overviewPages.plantOverview' })}${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}
                  className={cls([Styles.OpacityCard, Styles.OrderBox])}
                  extra={
                    <Radio.Group
                      defaultValue="realTime"
                      buttonStyle="solid"
                      onChange={handleChangeStatus}
                      value={batteryInfoSelected}
                      size="small"
                    >
                      <Radio.Button value="realTime">
                        {intl.formatMessage({ id: 'overviewPages.realTime' })}
                      </Radio.Button>
                      <Radio.Button value="baseTime">
                        {intl.formatMessage({ id: 'overviewPages.baseTime' })}
                      </Radio.Button>
                    </Radio.Group>
                  }
                >
                  {batteryInfoSelected === 'realTime' ? <RealTimePanel /> : <BaseTimePanel />}
                </Card>
                <div className={Styles.BatteryViewbg}>
                  <div className={Styles.BatteryBg}></div>
                  <div className={Styles.BatteryReport}>
                    <HealthReport date={moment().format('YYYY-MM-DD')} />
                  </div>
                  <div className={Styles.BatteryBox}>
                    <BatteryCard materials={filteredMaterials} />
                  </div>
                  <div className={Styles.BatteryInfoTips}>
                    <div className={cls([Styles.AlarmBox, Styles.LoadPower])}>
                      <p className={Styles.BatteryInfoTips__title}>
                        {intl.formatMessage({ id: 'overviewPages.loadPower' })}
                      </p>
                      <p>
                        <span className={Styles.BatteryInfoTips__primaryText}>
                          {stationMainData?.loadPower ? stationMainData?.loadPower : '--'}
                        </span>
                        <span className={Styles.BatteryInfoTips__unitText}>
                          {protocols?.includes('GLC') ? 'kVA' : 'kW'}
                        </span>
                      </p>
                    </div>
                    {!protocols?.includes('GLC') && (
                      <div className={cls([Styles.AlarmBox, Styles.GridPower])}>
                        <p className={Styles.BatteryInfoTips__title}>
                          {intl.formatMessage({ id: 'overviewPages.powerOfPOC' })}
                        </p>
                        <p>
                          <span className={Styles.BatteryInfoTips__primaryText}>
                            {stationMainData?.pocPower ? stationMainData?.pocPower : '--'}
                          </span>
                          <span className={Styles.BatteryInfoTips__unitText}>kW</span>
                        </p>
                      </div>
                    )}
                    <div className={cls([Styles.AlarmBox, Styles.StoragePower])}>
                      <p className={Styles.BatteryInfoTips__title}>
                        {intl.formatMessage({ id: 'overviewPages.realTimePower' })}
                      </p>
                      <p>
                        <span className={Styles.BatteryInfoTips__primaryText}>
                          {stationMainData?.totalPower ? stationMainData?.totalPower : '--'}
                        </span>
                        <span className={Styles.BatteryInfoTips__unitText}>kW</span>
                      </p>
                    </div>

                    {protocols?.includes('GLC') && (
                      <>
                        <div className={cls([Styles.AlarmBox, Styles.demandPower])}>
                          <p className={Styles.BatteryInfoTips__title}>
                            {intl.formatMessage({ id: 'overviewPages.demandPower' })}
                          </p>
                          <p>
                            <span className={Styles.BatteryInfoTips__primaryText}>
                              {stationMainData?.demandPower || '--'}
                            </span>
                            <span className={Styles.BatteryInfoTips__unitText}>kW</span>
                          </p>
                        </div>

                        <div className={cls([Styles.AlarmBox, Styles.refluxPower])}>
                          <p className={Styles.BatteryInfoTips__title}>
                            {intl.formatMessage({ id: 'overviewPages.refluxPower' })}
                          </p>
                          <p>
                            <span className={Styles.BatteryInfoTips__primaryText}>
                              {stationMainData?.refluxPower || '--'}
                            </span>
                            <span className={Styles.BatteryInfoTips__unitText}>kW</span>
                          </p>
                        </div>

                        <div className={cls([Styles.AlarmBox, Styles.realtimeDemand])}>
                          <p className={Styles.BatteryInfoTips__title}>
                            {intl.formatMessage({ id: 'overviewPages.realtimeDemand' })}
                          </p>
                          <p>
                            <span className={Styles.BatteryInfoTips__primaryText}>
                              {stationMainData?.realtimeDemand || '--'}
                            </span>
                            <span className={Styles.BatteryInfoTips__unitText}>kW</span>
                          </p>
                        </div>
                      </>
                    )}
                  </div>
                </div>
              </div>
              {isWide ? (
                ''
              ) : (
                <div className={Styles.BatteryViewWrap}>
                  <div className={Styles.BatteryViewBox}>
                    <Card
                      title={intl.formatMessage({ id: 'overviewPages.operationIndex' })}
                      className={Styles.OpacityCard}
                    >
                      <OperatingInfo statuses={stationStatuses} />
                    </Card>
                    <Card
                      title={
                        <div>
                          <Tooltip
                            title={`${intl.formatMessage({
                              id: 'overviewPages.betteryInfor',
                            })}
                  ${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}
                          >
                            <div
                              style={{
                                width: '12rem',
                                whiteSpace: 'nowrap' /* 不换行 */,
                                textAlign: 'left',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                              }}
                            >{`${intl.formatMessage({ id: 'overviewPages.betteryInfor' })}
                  ${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}</div>
                          </Tooltip>
                        </div>
                      }
                      className={Styles.OpacityCard}
                      extra={
                        <Link to={'/stationmonitor/realtime?battery=true'}>
                          <div
                            className={Styles.DetailText}
                            style={{ marginLeft: '10px', cursor: 'pointer', fontSize: '12px' }}
                          >
                            <span>{intl.formatMessage({ id: 'global.detail' })}</span>
                            <span>{'>'}</span>
                          </div>
                        </Link>
                      }
                    >
                      {stationBatteryData.map((battery, index) => (
                        <BatteryInfo
                          key={index}
                          stationSoc={battery?.stationSoc}
                          soc={{
                            min: battery?.soc?.min,
                            boxName: battery?.soc?.boxName,
                            max: battery?.soc?.max,
                          }}
                          temperature={{
                            min: battery?.temperature?.min,
                            boxName: battery?.temperature?.boxName,
                            max: battery?.temperature?.max,
                          }}
                          voltageExtreme={{
                            min: battery?.voltageExtreme?.min,
                            boxName: battery?.voltageExtreme?.boxName,
                            max: battery?.voltageExtreme?.max,
                          }}
                          currentExtreme={{
                            min: battery?.currentExtreme?.min,
                            boxName: battery?.currentExtreme?.boxName,
                            max: battery?.currentExtreme?.max,
                          }}
                          isOldStation={isOldStation}
                        />
                      ))}
                    </Card>
                  </div>
                </div>
              )}
            </div>
          </Col>
          <Col flex={'33%'}>
            {isWide ? (
              ''
            ) : (
              <div className={Styles.BatteryDetailsWrap}>
                <Card
                  className={Styles.OpacityCard}
                  title={`${intl.formatMessage({ id: 'overviewPages.latestEvents' })}${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}
                  extra={
                    <Flex align="center">
                      <Radio.Group
                        defaultValue={protocols?.includes('GLC') ? 'warningEvent' : 'baseEvent'}
                        buttonStyle="solid"
                        onChange={handleChangeEvent}
                        value={batteryEventelected}
                        size="small"
                      >
                        {!protocols?.includes('GLC') && (
                          <Radio.Button value="baseEvent">
                            {intl.formatMessage({ id: 'overviewPages.policyEvents' })}
                          </Radio.Button>
                        )}
                        <Radio.Button value="warningEvent">
                          {intl.formatMessage({ id: 'overviewPages.alarmEvents' })}
                        </Radio.Button>
                      </Radio.Group>
                      <Link to={linkTo}>
                        <div
                          className={Styles.DetailText}
                          style={{ marginLeft: '10px', cursor: 'pointer' }}
                        >
                          <span>{intl.formatMessage({ id: 'global.detail' })}</span>
                          <span>{'>'}</span>
                        </div>
                      </Link>
                    </Flex>
                  }
                >
                  {protocols?.includes('GLC') ? (
                    <WarningEventPanel />
                  ) : batteryEventelected === 'baseEvent' ? (
                    <BaseEventPanel />
                  ) : (
                    <WarningEventPanel />
                  )}
                </Card>
                <Card
                  title={
                    <div className={Styles.titleOverflow}>
                      <Tooltip
                        title={`${intl.formatMessage({
                          id: 'overviewPages.24HourOperation',
                        })}${
                          initialState?.areaInfo?.areaName
                            ? '_' + initialState?.areaInfo?.areaName
                            : ''
                        }`}
                      >
                        <div
                          style={{
                            width: '12rem',
                            whiteSpace: 'nowrap' /* 不换行 */,
                            textAlign: 'left',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                          }}
                        >
                          {`${intl.formatMessage({
                            id: 'overviewPages.24HourOperation',
                          })}${
                            initialState?.areaInfo?.areaName
                              ? '_' + initialState?.areaInfo?.areaName
                              : ''
                          }`}
                        </div>
                      </Tooltip>
                    </div>
                  }
                  extra={
                    <div className={Styles.colorMapWrap}>
                      <Link to={'/battery/workVal'}>
                        <div
                          className={Styles.DetailText}
                          style={{ marginLeft: '10px', cursor: 'pointer', fontSize: '12px' }}
                        >
                          <span>{intl.formatMessage({ id: 'global.detail' })}</span>
                          <span>{'>'}</span>
                        </div>
                      </Link>
                    </div>
                  }
                  className={cls([Styles.OpacityCard, Styles.ChartCard])}
                >
                  <ColorMapComponent />
                  <div className={Styles.PeakValleyWrap}>
                    <div className={Styles.PeakValley}>
                      {fengGuData.length > 0 && <PeakValleyChart fenggGuStateData={fengGuData} />}
                    </div>
                    <div className={Styles.WorkStateWrap}>
                      {workStateData.length > 0 && (
                        <WorkingConditionChart workStateData={workStateData} />
                      )}
                    </div>
                  </div>
                </Card>
                <Card
                  title={
                    <div className={Styles.titleOverflow}>
                      <Tooltip
                        title={`${intl.formatMessage({
                          id: 'overviewPages.chargeDischargeTimes',
                        })}
                  ${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}
                      >
                        <div
                          style={{
                            width: '15rem',
                            whiteSpace: 'nowrap' /* 不换行 */,
                            textAlign: 'left',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                          }}
                        >{`${intl.formatMessage({
                          id: 'overviewPages.chargeDischargeTimes',
                        })}
                  ${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}</div>
                      </Tooltip>
                    </div>
                  }
                  extra={
                    <Link to={'/statistics/electric'}>
                      <div
                        className={Styles.DetailText}
                        style={{ marginLeft: '10px', cursor: 'pointer' }}
                      >
                        <span>{intl.formatMessage({ id: 'global.detail' })}</span>
                        <span>{'>'}</span>
                      </div>
                    </Link>
                  }
                  className={Styles.OpacityCard}
                >
                  <DischargeInfo dataset={stationChargeAndDischarge} />
                </Card>
              </div>
            )}
          </Col>
        </Row>
        {isWide ? (
          <div className={Styles.Tablet}>
            <Flex justify="space-between" gap={20}>
              <div className={Styles.TabletCol}>
                <Flex vertical={true} gap={20}>
                  <Card
                    className={Styles.OpacityCard}
                    title={`${intl.formatMessage({ id: 'overviewPages.latestEvents' })}${
                      initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                    }`}
                    extra={
                      <Flex align="center">
                        <Radio.Group
                          defaultValue={protocols?.includes('GLC') ? 'warningEvent' : 'baseEvent'}
                          buttonStyle="solid"
                          onChange={handleChangeEvent}
                          value={batteryEventelected}
                          size="small"
                        >
                          {!protocols?.includes('GLC') && (
                            <Radio.Button value="baseEvent">
                              {intl.formatMessage({ id: 'overviewPages.policyEvents' })}
                            </Radio.Button>
                          )}
                          <Radio.Button value="warningEvent">
                            {intl.formatMessage({ id: 'overviewPages.alarmEvents' })}
                          </Radio.Button>
                        </Radio.Group>
                        <Link to={linkTo}>
                          <div
                            className={Styles.DetailText}
                            style={{ marginLeft: '10px', cursor: 'pointer' }}
                          >
                            <span>{intl.formatMessage({ id: 'global.detail' })}</span>
                            <span>{'>'}</span>
                          </div>
                        </Link>
                      </Flex>
                    }
                  >
                    {protocols?.includes('GLC') ? (
                      <WarningEventPanel />
                    ) : batteryEventelected === 'baseEvent' ? (
                      <BaseEventPanel />
                    ) : (
                      <WarningEventPanel />
                    )}
                  </Card>
                  <Card
                    title={`${intl.formatMessage({ id: 'overviewPages.24HourOperation' })}${
                      initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                    }`}
                    extra={
                      <div className={Styles.colorMapWrap}>
                        <Link to={'/battery/workVal'}>
                          <div
                            className={Styles.DetailText}
                            style={{ marginLeft: '10px', cursor: 'pointer', fontSize: '12px' }}
                          >
                            <span>{intl.formatMessage({ id: 'global.detail' })}</span>
                            <span>{'>'}</span>
                          </div>
                        </Link>
                      </div>
                    }
                    className={cls([Styles.OpacityCard, Styles.ChartCard])}
                  >
                    <ColorMapComponent />
                    <div className={Styles.PeakValleyWrap}>
                      <div className={Styles.PeakValley}>
                        {fengGuData && <PeakValleyChart fenggGuStateData={fengGuData} />}
                      </div>
                      <div className={Styles.WorkStateWrap}>
                        {workStateData && <WorkingConditionChart workStateData={workStateData} />}
                      </div>
                    </div>
                  </Card>
                  <Card
                    title={`${intl.formatMessage({ id: 'overviewPages.betteryInfor' })}${
                      initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                    }`}
                    className={Styles.OpacityCard}
                    extra={
                      <Link to={'/stationmonitor/realtime'}>
                        <div
                          className={Styles.DetailText}
                          style={{ marginLeft: '10px', cursor: 'pointer', fontSize: '12px' }}
                        >
                          <span>{intl.formatMessage({ id: 'global.detail' })}</span>
                          <span>{'>'}</span>
                        </div>
                      </Link>
                    }
                  >
                    {stationBatteryData.map((battery, index) => (
                      <BatteryInfo
                        key={index}
                        stationSoc={battery?.stationSoc}
                        soc={{
                          min: battery?.soc?.min,
                          boxName: battery?.soc?.boxName,
                          max: battery?.soc?.max,
                        }}
                        temperature={{
                          min: battery?.temperature?.min,
                          boxName: battery?.temperature?.boxName,
                          max: battery?.temperature?.max,
                        }}
                        voltageExtreme={{
                          min: battery?.voltageExtreme?.min,
                          boxName: battery?.voltageExtreme?.boxName,
                          max: battery?.voltageExtreme?.max,
                        }}
                        currentExtreme={{
                          min: battery?.currentExtreme?.min,
                          boxName: battery?.currentExtreme?.boxName,
                          max: battery?.currentExtreme?.max,
                        }}
                        isOldStation={isOldStation}
                      />
                    ))}
                  </Card>
                  <Card
                    styles={{
                      header: {
                        maxWidth: '12rem',
                        whiteSpace: 'nowrap' /* 不换行 */,
                        textAlign: 'center',
                        textOverflow: 'ellipsis',
                      },
                    }}
                    title={
                      <div>
                        <Tooltip
                          title={`${intl.formatMessage({
                            id: 'overviewPages.revenueStatistics',
                          })}
                  ${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}
                        >
                          <span>{`${intl.formatMessage({ id: 'overviewPages.revenueStatistics' })}
                  ${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}</span>
                        </Tooltip>
                      </div>
                    }
                    className={Styles.bottomCard}
                  >
                    <IncomeStatistics
                      incomeInfoOptions={incomeInfoOptions}
                      sendIncomeTimeInfo={getIncomeInfo}
                    />
                  </Card>
                  <Card title={powerChartCardTitle} className={Styles.bottomCard}>
                    <PowerChart powerChartInfo={powerChartInfo} />
                  </Card>
                </Flex>
              </div>
              <div className={Styles.TabletCol}>
                <Flex vertical={true} gap={20}>
                  <Card
                    title={intl.formatMessage({ id: 'overviewPages.operationIndex' })}
                    className={Styles.OpacityCard}
                  >
                    <OperatingInfo statuses={stationStatuses} />
                  </Card>
                  <Card
                    title={
                      <div className={Styles.titleOverflow}>
                        <Tooltip
                          title={`${intl.formatMessage({
                            id: 'overviewPages.chargeDischargeTimes',
                          })}
                  ${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}
                        >
                          <div
                            style={{
                              width: '15rem',
                              whiteSpace: 'nowrap' /* 不换行 */,
                              textAlign: 'left',
                              overflow: 'hidden',
                              textOverflow: 'ellipsis',
                            }}
                          >{`${intl.formatMessage({
                            id: 'overviewPages.chargeDischargeTimes',
                          })}
                  ${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}</div>
                        </Tooltip>
                      </div>
                    }
                    extra={
                      <Link to={'/statistics/electric'}>
                        <div
                          className={Styles.DetailText}
                          style={{ marginLeft: '10px', cursor: 'pointer' }}
                        >
                          <span>{intl.formatMessage({ id: 'global.detail' })}</span>
                          <span>{'>'}</span>
                        </div>
                      </Link>
                    }
                    className={Styles.OpacityCard}
                  >
                    <DischargeInfo dataset={stationChargeAndDischarge} />
                  </Card>
                  <Card
                    title={`${intl.formatMessage({
                      id: 'overviewPages.chargeDischargeStatistics',
                    })}`}
                    className={Styles.bottomCard}
                  >
                    <PowerStatistics
                      chargeInfoOptions={chargeInfoOptions}
                      sendChargeInfo={getChargeInfo}
                    />
                  </Card>
                </Flex>
              </div>
            </Flex>
          </div>
        ) : (
          ''
        )}
        {isWide ? (
          ''
        ) : (
          <Flex justify="space-between" className={Styles.ChartContent}>
            <Card
              title={
                <div className={Styles.titleOverflow}>
                  <Tooltip
                    title={`${intl.formatMessage({ id: 'overviewPages.revenueStatistics' })}
                  ${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}
                  >
                    <div
                      style={{
                        width: '9rem',
                        whiteSpace: 'nowrap' /* 不换行 */,
                        textAlign: 'left',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                      }}
                    >
                      {`${intl.formatMessage({ id: 'overviewPages.revenueStatistics' })}
                  ${
                    initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                  }`}
                    </div>
                  </Tooltip>
                </div>
              }
              className={Styles.bottomCard}
            >
              <IncomeStatistics
                incomeInfoOptions={incomeInfoOptions}
                sendIncomeTimeInfo={getIncomeInfo}
              />
            </Card>
            <Card
              styles={{}}
              title={
                <div className={Styles.titleOverflow}>
                  <Tooltip
                    title={`${intl.formatMessage({
                      id: 'overviewPages.chargeDischargeStatistics',
                    })}${
                      initialState?.areaInfo?.areaName ? '_' + initialState?.areaInfo?.areaName : ''
                    }`}
                  >
                    <div
                      style={{
                        width: '12rem',
                        whiteSpace: 'nowrap' /* 不换行 */,
                        textAlign: 'left',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                      }}
                    >
                      {`${intl.formatMessage({ id: 'overviewPages.chargeDischargeStatistics' })}${
                        initialState?.areaInfo?.areaName
                          ? '_' + initialState?.areaInfo?.areaName
                          : ''
                      }`}
                    </div>
                  </Tooltip>
                </div>
              }
              className={Styles.bottomCard}
            >
              <PowerStatistics
                chargeInfoOptions={chargeInfoOptions}
                sendChargeInfo={getChargeInfo}
              />
            </Card>
            <Card title={powerChartCardTitle} className={Styles.bottomCard}>
              <PowerChart powerChartInfo={powerChartInfo} />
            </Card>
          </Flex>
        )}

        {/* <div className={Styles.bg}></div> */}
        {/*<div className={Styles.Report}>*/}
        {/*  <MonthlyReport isViewFlag={true} />*/}
        {/*</div>*/}
      </div>
    )
  ) : // for old station
  isSmallViewport ? (
    <div
      style={{
        width: '100%',
        minHeight: '100%',
        display: 'grid',
        gridTemplateColumns: 'repeat(2, minmax(480px, 1fr))',
        // gridTemplateRows: '140px 340px 240px 320px 320px',
        gridTemplateRows: isEnglish
          ? 'auto auto auto 320px 320px'
          : '140px 340px 240px 320px 320px',
        gap: '20px',
      }}
    >
      <div style={{ gridColumn: '1/3', gridRow: '1', backgroundColor: '#cbd5e1' }}>
        {overviewOfPowerPlant}
      </div>

      <div style={{ gridColumn: '1', gridRow: '2', backgroundColor: '#cbd5e1' }}>
        {performanceMetrics}
      </div>
      <div style={{ gridColumn: '2', gridRow: '2', backgroundColor: '#cbd5e1' }}>
        {chargeAndDischargeStatistics}
      </div>

      <div style={{ gridColumn: '1', gridRow: '3', backgroundColor: '#cbd5e1' }}>{batteryInfo}</div>
      <div style={{ gridColumn: '2', gridRow: '3', backgroundColor: '#cbd5e1' }}>
        <BatteryEvents />
      </div>

      <div style={{ gridColumn: '1', gridRow: '4', backgroundColor: '#cbd5e1' }}>
        <DailyDischargeDepthCurve />
      </div>
      <div style={{ gridColumn: '2', gridRow: '4', backgroundColor: '#cbd5e1' }}>
        {chargeAndDischargePowerCurve}
      </div>

      <div style={{ gridColumn: '1', gridRow: '5', backgroundColor: '#cbd5e1' }}>
        <DailyChargeDischargeConversionEfficiency />
      </div>
    </div>
  ) : (
    <div
      style={{
        width: '100%',
        minHeight: '100%',
        display: 'flex',
        gap: '20px',
      }}
    >
      <div
        style={{
          flex: 2,
          display: 'grid',
          gridTemplateColumns: 'repeat(2, minmax(480px, 1fr))',
          // gridTemplateRows: '140px 340px 320px',
          gridTemplateRows: isEnglish ? '200px 360px 340px' : '140px 360px 340px',
          gap: '20px',
        }}
      >
        <div style={{ gridColumn: '1/3', gridRow: '1', backgroundColor: '#cbd5e1' }}>
          {overviewOfPowerPlant}
        </div>
        <div style={{ gridColumn: '1', gridRow: '2', backgroundColor: '#cbd5e1' }}>
          {performanceMetrics}
        </div>
        <div style={{ gridColumn: '2', gridRow: '2', backgroundColor: '#cbd5e1' }}>
          {chargeAndDischargeStatistics}
        </div>
        <div style={{ gridColumn: '1', gridRow: '3', backgroundColor: '#cbd5e1' }}>
          {chargeAndDischargePowerCurve}
        </div>
        <div style={{ gridColumn: '2', gridRow: '3', backgroundColor: '#cbd5e1' }}>
          <DailyChargeDischargeConversionEfficiency />
        </div>
      </div>
      <div
        style={{
          flex: 1,
          display: 'grid',
          gridTemplateColumns: 'minmax(480px, 1fr)',
          // gridTemplateRows: '240px 240px 320px',
          gridTemplateRows: isEnglish ? '260px 260px 380px' : '280px 240px 320px',
          gap: '20px',
        }}
      >
        <div style={{ gridColumn: '1', gridRow: '1', backgroundColor: '#cbd5e1' }}>
          {batteryInfo}
        </div>
        <div style={{ gridColumn: '1', gridRow: '2', backgroundColor: '#cbd5e1' }}>
          <BatteryEvents />
        </div>
        <div style={{ gridColumn: '1', gridRow: '3', backgroundColor: '#cbd5e1' }}>
          <DailyDischargeDepthCurve />
        </div>
      </div>
    </div>
  );
};

export default OverView;
